# Copyright © 2025 kskou. All rights reserved.

# The software and associated documentation files (the "Software") provided in this tool are the property of kskou. Unauthorized reproduction, distribution, or modification of the Software, in whole or in part, is strictly prohibited. Any use of the Software must comply with applicable laws and regulations and obtain prior written permission from kskou.

# DISCLAIMER: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL kskou BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import requests
import json

# 禁用 SSL 证书验证（仅用于测试环境）
requests.packages.urllib3.disable_warnings()

def read_config():
    try:
        with open('config.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        print("配置文件 config.json 未找到，请检查。")
        return None
    except json.JSONDecodeError:
        print("配置文件 config.json 格式错误，请检查。")
        return None

def get_bios_settings_url(redfish_url, username, password):
    try:
        response = requests.get(f"{redfish_url}/Systems/1", auth=(username, password), verify=False)
        response.raise_for_status()
        system_data = response.json()
        bios_url = system_data.get("Bios", {}).get("@odata.id")
        if bios_url.startswith("/redfish/v1"):
            bios_url = bios_url[len("/redfish/v1"):]
        # 添加 /settings
        #bios_url = f"{bios_url}/settings"
        return bios_url
    except requests.RequestException as e:
        print(f"请求出错: {e}，设备地址: {redfish_url}")
        return None

def get_all_bios_settings(redfish_url, bios_url, username, password):
    all_settings = {}
    current_url = f"{redfish_url}{bios_url}"
    while current_url:
        try:
            response = requests.get(current_url, auth=(username, password), verify=False)
            response.raise_for_status()
            settings = response.json()
            all_settings.update(settings)
            current_url = settings.get('@odata.nextLink')
        except requests.RequestException as e:
            print(f"获取 BIOS 设置失败: {e}，设备地址: {redfish_url}，响应内容: {response.text if 'response' in locals() else '无'}")
            break
    return all_settings

def main():
    config = read_config()
    if config:
        for device in config:
            redfish_url = device['redfish_url']
            username = device['username']
            password = device['password']

            bios_url = get_bios_settings_url(redfish_url, username, password)
            if bios_url:
                bios_settings = get_all_bios_settings(redfish_url, bios_url, username, password)
                if bios_settings:
                    # 提取 IP 地址
                    ip = redfish_url.split('//')[1].split('/')[0]
                    filename = f"{ip}_bios_settings.json"
                    try:
                        with open(filename, 'w') as f:
                            json.dump(bios_settings, f, indent=4)
                        print(f"BIOS 设置已导出到 {filename}")
                    except Exception as e:
                        print(f"导出文件 {filename} 时出错: {e}")

if __name__ == "__main__":
    main()